package benchmarks;
//TODO moet een custom ser/deser schrijven
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;

import edu.vub.at.objects.natives.NATText;

public class JacksonLib implements TestMethods {

	public static ObjectMapper mapper;
	
	public JacksonLib() {
		mapper = new ObjectMapper();		
		mapper.registerModule(new NATTextModule());
	}
	
	public final class NATTextDeserializer extends JsonDeserializer<NATText> {

	    @Override
	    public NATText deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
	            throws IOException, JsonProcessingException {
	        if (jsonParser.getCurrentToken() == JsonToken.VALUE_STRING) {
	            return NATText.atValue(jsonParser.getText());
	        }

	        throw deserializationContext.mappingException("Expected JSON Number");
	    }
	}
	
	public final class NATTextSerializer extends JsonSerializer<NATText> {

	    @Override
	    public void serialize(NATText value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
	        JsonProcessingException {
	        jgen.writeString(value.javaValue);
	    }
	}

	
	public final class NATTextModule extends SimpleModule {
	    public NATTextModule() {
	        addDeserializer(NATText.class, new NATTextDeserializer());
	        addSerializer(NATText.class, new NATTextSerializer());
	    }
	}
	
	@Override
	public byte[] serialize(Object o) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		mapper.writeValue(out, o.getClass());
		return out.toByteArray();
	}

	@Override
	public Object deserialize(byte[] b, Class c) throws IOException,
			ClassNotFoundException {
		ByteArrayInputStream in = new ByteArrayInputStream(b);
		return mapper.readValue(in, c);
	}

	@Override
	public Object copy(Object o) throws IOException, ClassNotFoundException {
		return deserialize(serialize(o), o.getClass());
	}

}
